const md5 = require('md5')
const dataBase = require('../../mysql')

const sql = require('../../mysql/sql')
const verifyRequestMethod = require('../../tool/verifyRequestMethod')

/**
 * @description 注册
 */
module.exports = function () {
    const that = this
    /**
     * @description 请求验证
     */
    verifyRequestMethod(this.request, 'POST').then(function () {
        /**
         * @description 获取body
         */
        return that.getBodyData(that.request)
    }).then(function (body) {
        /**
         * @description 表单验证
         */
        if (!body.username) {
            that.response.outPrintError('账号不能为空，请输入账号！')
        } else if (!/^[1-9]\d{9}$/.test(body.username)) {
            that.response.outPrintError('账号只能是数字，并且长度只能为10位，不能以0开头或，负数！')
        } else if (!body.password) {
            that.response.outPrintError('密码不能为空，请输入密码！')
        } else if (!/^(?=.*\d)(?=.*[a-zA-Z]).{6,20}$/.test(body.password)) {
            that.response.outPrintError('密码至少6个字符最多20个字符，至少1个大写字母或1个小写字母，和1个数字！')
        } else {
            /**
             * @description 查询所有的ID
             */
            return dataBase.connect(sql.SQL_USER_ID_COUNT()).then(function (result) {
                return Promise.resolve({
                    list: result,
                    body: body
                })
            })
        }
    }).then(function (result) {
        /**
         * @description 重复验证
         */
        if (result.list.map(function (item) {
            item = item.username
            return item
        }).includes(parseInt(result.body.username))) {
            that.response.outPrintError('账号已被注册，请重新输入！')
        } else {
            return dataBase.connect(sql.SQL_ADD_USER_ONE(result.body.username, md5(result.body.password)))
        }
    }).then(function (result) {
        that.response.outPrintData({}, '注册成功！')
    }).catch(function (e) {
        that.response.outPrintError((e && e.message) || '未知错误！')
    })
}